package com.jiyun.jiyunmall.product.controller;

import com.jiyun.jiyunmall.common.annotation.LogOperation;
import com.jiyun.jiyunmall.common.constant.Constant;
import com.jiyun.jiyunmall.common.page.PageData;
import com.jiyun.jiyunmall.common.utils.ExcelUtils;
import com.jiyun.jiyunmall.common.utils.Result;
import com.jiyun.jiyunmall.common.valid.SaveGroup;
import com.jiyun.jiyunmall.common.validator.AssertUtils;
import com.jiyun.jiyunmall.common.validator.ValidatorUtils;
import com.jiyun.jiyunmall.common.validator.group.AddGroup;
import com.jiyun.jiyunmall.common.validator.group.DefaultGroup;
import com.jiyun.jiyunmall.common.validator.group.UpdateGroup;
import com.jiyun.jiyunmall.product.dto.BrandDTO;
import com.jiyun.jiyunmall.product.excel.BrandExcel;
import com.jiyun.jiyunmall.product.service.BrandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 品牌
 *
 * @author boge 71164376@qq.com
 * @since 1.0.0 2022-07-12
 */
@RestController
@RequestMapping("product/brand")
@Api(tags="品牌")
public class BrandController {
    @Autowired
    private BrandService brandService;
    @Value("${oss.host}")
    private  String host;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<BrandDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<BrandDTO> page = brandService.page(params);
        for (BrandDTO brandDTO : page.getList()) {
            brandDTO.setLogo(host+brandDTO.getLogo());
        }
        return new Result<PageData<BrandDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<BrandDTO> get(@PathVariable("id") Long id){
        BrandDTO data = brandService.get(id);
        data.setPrefix(host);
        return new Result<BrandDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    public Result save(@Valid @RequestBody BrandDTO dto/*, BindingResult bindingResult*/){
        // BindingResult bindingResult：如果绑定出异常，自动将发生的异常返回结果，注入到BindingResult中
        // 你可以在处理器方法中，注入该对象，通过该对象，获取这些信息
        // 以当前场景为例：如果Valid校验JSR303失败，自动将错误信息封装到BindingResult，你可以通过它获取相关信息，并处理
//        System.out.println(bindingResult);
//        if(bindingResult.getErrorCount()>0){
//            List<ObjectError> allErrors = bindingResult.getAllErrors();
//            // 比如：如果同时发生两个JSR303校验失败，你可以先返回一个，也可以两个同时返回
//            ArrayList<String> strings = new ArrayList<>();
//            for (ObjectError allError : allErrors) {
//                //封装结果集，并返回
//                strings.add(allError.getDefaultMessage());
//            }
//            Result<ArrayList<String>> arrayListResult = new Result<>();
//            arrayListResult.setData(strings);
//            arrayListResult.setCode(400);
//            return arrayListResult;
//        }
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        brandService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    public Result update(@Validated({UpdateGroup.class}) @RequestBody BrandDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        brandService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        brandService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<BrandDTO> list = brandService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, BrandExcel.class);
    }

}